package com.cn.longdistancebusstation.stationList;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SearchView;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.cn.longdistancebusstation.annotation.HolderViewType;
import com.cn.longdistancebusstation.base.BaseActivity;
import com.cn.longdistancebusstation.callback.OnRecyclerViewItemClickListener;

import com.cn.longdistancebusstation.R;
import com.cn.longdistancebusstation.customView.IndexSideBar;
import com.cn.longdistancebusstation.httpHelper.HttpHelper;
import com.cn.longdistancebusstation.httpapi.WebService;
import com.cn.longdistancebusstation.model.Station;
import com.cn.longdistancebusstation.personal.CouponsActivity;
import com.nostra13.universalimageloader.utils.L;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

import java.io.IOException;
import java.io.StringReader;
import java.lang.reflect.Method;
import java.text.Collator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.zip.Inflater;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

public class StationListActivity extends BaseActivity implements OnRecyclerViewItemClickListener {

    private SearchView mSearchView;
    private RecyclerView mRecyclerView;
    private IndexSideBar mIndexSideBar;
    private List<Station> mStationlist;
    private List<Object> mDataSourceList;
    private List<Station> mResultsList;
    private List<String> mIndexList;
    private Map<String, String> mIndexMap;
    private CustomAdapter mAdapter;
    private Boolean mIsSearch;
    private ArrayFilter mFilter;
    private LinearLayout mLinearLayout;
    private RelativeLayout mRelativeLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_station_list);
        //设置标题
        this.getTitleTextView().setText("站点列表");
        prepareData();
    }

    private void prepareData(){
        mIsSearch = false;
        mStationlist = new ArrayList<>();
        mDataSourceList = new ArrayList<>();
        mIndexList = new ArrayList<>();
        mIndexMap = new HashMap<>();
        mResultsList = new ArrayList<>();
        mSearchView = (SearchView)findViewById(R.id.searchView);
        mRecyclerView = (RecyclerView)findViewById(R.id.recyclerView);
        mIndexSideBar = (IndexSideBar)findViewById(R.id.indexSideBar);
        mIndexSideBar.setBackgroundColor(Color.rgb(241,241,241));
        mIndexSideBar.setOnLetterTouchedChangeListener(new IndexSideBar.OnLetterTouchedChangeListener() {
            @Override
            public void onTouchedLetterChange(String letterTouched) {
                int pos = Integer.parseInt(mIndexMap.get(letterTouched));
                if(pos!=-1){
                    mRecyclerView.scrollToPosition(pos);
                }
            }
        });
        //
        mSearchView.setIconifiedByDefault(false);
        mSearchView.setQueryHint("目的地");
        mSearchView.setFocusable(false);
        mSearchView.setOnQueryTextFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
            }
        });
        mSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                if(query.length() == 0){
                    mSearchView.clearFocus();
                    mIsSearch = false;
                }
                else{
                    mSearchView.clearFocus();
                }
                return true;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                if(newText.length()>0){
                    mIsSearch = true;
                    mAdapter.getFilter().filter(newText);
                }
                else{
                    mIsSearch = false;
                    mAdapter.getFilter().filter(null);
                }
                mAdapter.notifyDataSetChanged();
                return true;
            }
        });
        mSearchView.setOnCloseListener(new SearchView.OnCloseListener() {
            @Override
            public boolean onClose() {
                mSearchView.setFocusable(false);
                return false;
            }
        });
        //
        mAdapter = new CustomAdapter();
        mAdapter.setOnItemClickListener(this);
        //
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mRecyclerView.setAdapter(mAdapter);
        mRecyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
        //
        mLinearLayout=(LinearLayout)findViewById(R.id.main_layout);
        mRelativeLayout=(RelativeLayout)findViewById(R.id.child_layout);
        getDesPorts();
    }

    /*
    * 获取所有目的站点
    * */
    private void getDesPorts(){
        showHud("加载中...");
        Retrofit retrofit = new HttpHelper.WebServiceBuilder().build().getRetrofit();
        WebService webService = retrofit.create(WebService.class);
        Call<String> call = webService.getDesPorts();
        call.enqueue(new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                hideHud();
                try
                {
                    parseXMLForDesPorts(response.body());
                    //排序
                    Comparator<Object> comparator = Collator.getInstance(Locale.CHINA);
                    Collections.sort(mStationlist, new Comparator<Station>() {
                        Collator collator = Collator.getInstance(Locale.CHINA);
                        @Override
                        public int compare(Station station, Station t1) {
                            String strCode0 = station.getStationCode();
                            String strCode1 = t1.getStationCode();
                            if(collator.compare(strCode0, strCode1)>0)
                            {
                                return 1;
                            }
                            else
                            {
                                return -1;
                            }
                        }
                    });
                    //获取索引
                    reOrganizeDataSource();
                    mIndexSideBar.setIndexList(mIndexList);
                    mAdapter.notifyDataSetChanged();
                }
                catch(XmlPullParserException e)
                {}
                catch(IOException e)
                {}
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {
                hideHud();
            }
        });

    }

    /*
    * 解析xml
    * */
    private void parseXMLForDesPorts(String xmlText) throws XmlPullParserException,IOException{
        mStationlist.clear();
        XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
        factory.setNamespaceAware(true);
        XmlPullParser xmlPullParser = factory.newPullParser();
        xmlPullParser.setInput(new StringReader(xmlText));
        Log.d("车站目的地数据",xmlText);
        int eventType = xmlPullParser.getEventType();
        String strTagName = "";
        Station station = null;
        while(eventType != XmlPullParser.END_DOCUMENT){
            if(eventType == XmlPullParser.START_DOCUMENT)
            {}
            else if(eventType == XmlPullParser.START_TAG)
            {
                strTagName = xmlPullParser.getName();
                if(strTagName.equals("portList"))
                {
                    station = new Station();
                }
            }
            else if(eventType == XmlPullParser.END_TAG)
            {
                strTagName = "";
                if(xmlPullParser.getName().equals("portList"))
                {
                    mStationlist.add(station);
                }
            }
            else if(eventType == XmlPullParser.TEXT)
            {
                if(strTagName.equals("PortID"))
                {
                    station.setStationID(xmlPullParser.getText());
                }
                else if(strTagName.equals("PortName"))
                {
                    station.setStationName(xmlPullParser.getText());
                }
                else if(strTagName.equals("PortCode"))
                {
                    station.setStationCode(xmlPullParser.getText());
                }
            }
            eventType = xmlPullParser.next();
        }
        if(mStationlist.size()==0){
            mLinearLayout.setVisibility(View.GONE);
            mRelativeLayout.setVisibility(View.VISIBLE);
        }else {
            mLinearLayout.setVisibility(View.VISIBLE);
            mRelativeLayout.setVisibility(View.GONE);
        }
    }

    /*
    * 组织数据
    * */
    private void reOrganizeDataSource(){
        for (int i = 0; i < mStationlist.size(); i++) {
            Station station = mStationlist.get(i);
            Station preStation = null;
            //
            CustomItemObj customItemObj = null;
            //
            String strIndex = station.getStationCode().substring(0, 1);
            //上一个站点的首字母
            String strPreIndex = "";
            if (i == 0) {
                //
                mIndexList.add(strIndex);
                mIndexMap.put(strIndex, mDataSourceList.size()+"");
                //
                IndexObj indexObj = new IndexObj();
                indexObj.setContent(strIndex);
                indexObj.setPos(mDataSourceList.size());
                //
                customItemObj = new CustomItemObj();
                customItemObj.setType(HolderViewType.HOLDER_VIEW_TYPE_HEADER);
                customItemObj.setData(indexObj);
                mDataSourceList.add(customItemObj);
                //
                customItemObj = new CustomItemObj();
                customItemObj.setType(HolderViewType.HOLDER_VIEW_TYPE_ITEM);
                customItemObj.setData(station);
                mDataSourceList.add(customItemObj);
            } else {
                preStation = mStationlist.get(i-1);
                strPreIndex = preStation.getStationCode().substring(0, 1);
                if (strIndex.equals(strPreIndex)) {
                    customItemObj = new CustomItemObj();
                    customItemObj.setType(HolderViewType.HOLDER_VIEW_TYPE_ITEM);
                    customItemObj.setData(station);
                    mDataSourceList.add(customItemObj);
                } else {
                    mIndexList.add(strIndex);
                    mIndexMap.put(strIndex, mDataSourceList.size()+"");
                    //
                    IndexObj indexObj = new IndexObj();
                    indexObj.setContent(strIndex);
                    indexObj.setPos(mDataSourceList.size());
                    //
                    customItemObj = new CustomItemObj();
                    customItemObj.setType(HolderViewType.HOLDER_VIEW_TYPE_HEADER);
                    customItemObj.setData(indexObj);
                    mDataSourceList.add(customItemObj);
                    //
                    customItemObj = new CustomItemObj();
                    customItemObj.setType(HolderViewType.HOLDER_VIEW_TYPE_ITEM);
                    customItemObj.setData(station);
                    mDataSourceList.add(customItemObj);
                }
            }
        }
    }

    @Override
    public void onClick(int position) {
        Station station = null;
        if(mIsSearch){
            station = mResultsList.get(position);
        }
        else{
            CustomItemObj customItemObj = (CustomItemObj) mDataSourceList.get(position);
            station = (Station)customItemObj.getData();
        }
        Intent intent = getIntent();
        intent.putExtra("station", station);
        setResult(RESULT_OK, intent);
        finish();
    }

    @Override
    public void onClickInnerCtrl(int position) {

    }

    @Override
    public void onClickCoupon(int position) {


    }

    @Override
    public void onClickCheckBox(int position) {

    }

    /*
    *
    * */
    private class ItemViewHolder extends RecyclerView.ViewHolder{
        private TextView mTextView;
        public ItemViewHolder(View itemView){
            super(itemView);
            mTextView = (TextView)itemView;
            mTextView.setTextColor(Color.BLACK);
        }

        public void bindData(String content){
            mTextView.setText(content);
        }
    }

    private class CustomAdapter extends RecyclerView.Adapter<ItemViewHolder> implements Filterable{
        private OnRecyclerViewItemClickListener mOnItemClickListener;

        public OnRecyclerViewItemClickListener getOnItemClickListener() {
            return mOnItemClickListener;
        }

        public void setOnItemClickListener(OnRecyclerViewItemClickListener onItemClickListener) {
            mOnItemClickListener = onItemClickListener;
        }

        @Override
        public Filter getFilter() {
            if(mFilter == null){
                mFilter = new ArrayFilter();
            }
            return mFilter;
        }

        @Override
        public ItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            LayoutInflater layoutInflater = LayoutInflater.from(getApplicationContext());
            View view = null;
            switch(viewType)
            {
                case HolderViewType.HOLDER_VIEW_TYPE_ITEM:
                {
                    view = layoutInflater.inflate(android.R.layout.simple_list_item_1, parent, false);
                    view.setBackgroundColor(Color.WHITE);
                }
                break;
                case HolderViewType.HOLDER_VIEW_TYPE_HEADER:
                {
                    view = layoutInflater.inflate(android.R.layout.simple_list_item_1, parent, false);
                    view.setBackgroundColor(Color.LTGRAY);
                }
                break;
                case HolderViewType.HOLDER_VIEW_TYPE_FOOTER:
                {}
            }

            return new ItemViewHolder(view);
        }

        @Override
        public void onBindViewHolder(ItemViewHolder holder, final int position) {
            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if(mIsSearch){
                        mOnItemClickListener.onClick(position);
                    }
                    else{
                        CustomItemObj customItemObj = (CustomItemObj) mDataSourceList.get(position);
                        if(customItemObj.getType()==HolderViewType.HOLDER_VIEW_TYPE_ITEM){
                            mOnItemClickListener.onClick(position);
                        }
                    }
                }
            });
            if(mIsSearch){
                Station station = (Station)mResultsList.get(position);
                String strContent = station.getStationName();
                holder.bindData(strContent);
                return;
            }
            CustomItemObj customItemObj = (CustomItemObj)mDataSourceList.get(position);
            String strContent = "";
            switch (customItemObj.getType()){
                case HolderViewType.HOLDER_VIEW_TYPE_HEADER:
                {
                    IndexObj indexObj = (IndexObj)customItemObj.getData();
                    strContent = indexObj.getContent();
                }
                break;
                case HolderViewType.HOLDER_VIEW_TYPE_ITEM:
                {
                    Station station = (Station)customItemObj.getData();
                    strContent = station.getStationName();
                }
                break;
                case HolderViewType.HOLDER_VIEW_TYPE_FOOTER:
                {}
                break;
            }

            holder.bindData(strContent);
        }

        @Override
        public int getItemCount() {
            if(mIsSearch)
            {
                if(mResultsList == null) return 0;
                return mResultsList.size();
            }
            else
            {
                return mDataSourceList.size();
            }
        }

        @Override
        public int getItemViewType(int position) {
            if(mIsSearch){
                return HolderViewType.HOLDER_VIEW_TYPE_ITEM;
            }
            else{
                CustomItemObj customItemObj = (CustomItemObj)mDataSourceList.get(position);
                return customItemObj.getType();
            }
        }


    }
    private class ArrayFilter extends Filter{
        private final Object mLock = new Object();
        private List<Station> mOriginalValues;
        @Override
        protected FilterResults performFiltering(CharSequence charSequence) {
            FilterResults filterResults = new FilterResults();
            String prefix = charSequence.toString();
            String keyWrold;

            if (mOriginalValues == null) {
                synchronized (mLock) {
                    mOriginalValues = new ArrayList<Station>(mStationlist);
                }
            }

            if (prefix == null || prefix.length() == 0) {
                ArrayList<Station> list;
                synchronized (mLock) {
                    list = new ArrayList<Station>(mOriginalValues);
                }
                filterResults.values = list;
                filterResults.count = list.size();
                keyWrold = "";
            } else {
                String prefixString = prefix.toString().toLowerCase();
                ArrayList<Station> values;
                synchronized (mLock) {
                    values = new ArrayList<Station>(mOriginalValues);
                }

                final int count = values.size();
                final ArrayList<Station> newValues = new ArrayList<Station>();

                for (int i = 0; i < count; i++) {
                    final Station station = values.get(i);
                    final String valueText = station.getStationName();
                    // First match against the whole, non-splitted value
                    if (valueText.contains(prefixString)) {
                        newValues.add(station);
                        keyWrold = prefixString;
                    }
                }

                filterResults.values = newValues;
                filterResults.count = newValues.size();
            }

            return filterResults;
        }

        @Override
        protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
            mResultsList = (List<Station>) filterResults.values;
            if (filterResults.count > 0) {
                mAdapter.notifyDataSetChanged();
            } else {
            }
        }
    }
    /*
    * recyclerView的item对象
    * */
    private class CustomItemObj {
        private
        int mType;
        private Object mData;

        public int getType() {
            return mType;
        }

        public void setType(int type) {
            mType = type;
        }

        public Object getData() {
            return mData;
        }

        public void setData(Object data) {
            mData = data;
        }
    }
    /*
    * 自定义索引对象
    * */
    private class  IndexObj{
        private int mPos;
        private String mContent;

        public int getPos() {
            return mPos;
        }

        public void setPos(int pos) {
            mPos = pos;
        }

        public String getContent() {
            return mContent;
        }

        public void setContent(String content) {
            mContent = content;
        }
    }
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideInput(v, ev)) {

                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
            }
            return super.dispatchTouchEvent(ev);
        }
        // 必不可少，否则所有的组件都不会有TouchEvent了
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);
    }
    /**
     * 根据EditText所在坐标和用户点击的坐标相对比，来判断是否隐藏键盘，因为当用户点击EditText时没必要隐藏
     *
     * @param v
     * @param event
     * @return
     */
    private boolean isShouldHideInput(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] leftTop = { 0, 0 };
            //获取输入框当前的location位置
            v.getLocationInWindow(leftTop);
            int left = leftTop[0];
            int top = leftTop[1];
            int bottom = top + v.getHeight();
            int right = left + v.getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                // 点击的是输入框区域，保留点击EditText的事件
                return false;
            } else {
                return true;
            }
        }
        return false;
    }

}
